package com.xzzz.irda.guardcat.server.repos.mysql;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xzzz.common.base.util.BeanUtil;
import com.xzzz.irda.guardcat.server.app.pojo.MachineInfo;
import com.xzzz.irda.guardcat.server.metric.MetricRepository;
import com.xzzz.irda.guardcat.server.repos.mysql.mappers.ThreadMapper;
import com.xzzz.irda.guardcat.server.metric.thread.ThreadInfo;
import com.xzzz.irda.guardcat.server.repos.mysql.pojo.ThreadMySQLEntity;
import com.xzzz.irda.tracker.core.adapter.aspect.TrackerStart;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;

@Slf4j
public class ThreadRepositoryInMySQL extends MetricRepository<ThreadInfo> {

    @Autowired
    private ThreadMapper threadMapper;

    @Override
    public void save(MachineInfo machineInfo, ThreadInfo threadInfo) {
        ThreadMySQLEntity entity = toEntity(threadInfo);
        entity.setAppName(machineInfo.getAppName());
        entity.setMachineId(machineInfo.getMachineId());
        threadMapper.insert(entity);
    }

    @Override
    @TrackerStart
    @Scheduled(cron = "0 0/1 * * * ?")
    public void expire() {
        long start = System.currentTimeMillis();
        Date today = DateUtil.date();
        // 删除1天前的
        Date expireDate = DateUtil.offsetDay(today, -1);
        String expireDateStr = DateUtil.format(expireDate, "yyyy-MM-dd HH:mm:ss");

        QueryWrapper<ThreadMySQLEntity> query = new QueryWrapper<>();
        query.le("cre_time", expireDate);
        int num = threadMapper.delete(query);
        log.info("[GUARDCAT] 删除小于 [{}]THREAD信息, 共:[{}], 用时: {}", expireDateStr, num, System.currentTimeMillis() - start);
    }

    @Override
    public ThreadInfo getByMachineId(String machineId) {
        return null;
    }

    @Override
    public List<ThreadInfo> listByMachineId(String machineId) {
        LambdaQueryWrapper<ThreadMySQLEntity> query = new LambdaQueryWrapper<ThreadMySQLEntity>()
                .eq(ThreadMySQLEntity::getMachineId, machineId)
                .orderByDesc(ThreadMySQLEntity::getCreTime)
                .last("limit 1500");
        return BeanUtil.toList(threadMapper.selectList(query), ThreadInfo.class);
    }

    public ThreadInfo entityTo(ThreadMySQLEntity entity) {
        ThreadInfo info = BeanUtil.toObj(entity, ThreadInfo.class);
        return info;
    }

    public ThreadMySQLEntity toEntity(ThreadInfo info) {
        ThreadMySQLEntity entity = BeanUtil.toObj(info, ThreadMySQLEntity.class);
        return entity;
    }
}
